<template>
  <div id="InterfaceParamDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="isEmpty(interfaceParamId)" @click="findInterfaceParamList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="isEmpty(interfaceParamId)" @click="addInterfaceParam"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="isEmpty(interfaceParamId)" @click="saveBathInterfaceParam"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="复制" :disabled="isEmpty(interfaceParamId)" @click="copy"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="粘贴" :disabled="isEmpty(interfaceParamId)" @click="paste"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="isEmpty(interfaceParamId)" @click="deleteInterfaceParam"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="InterfaceParamTableRef" class="mytable-scrollbar" border="inner" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="detailList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="seq" title="序号" width="50" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="number"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="code" title="字段名" width="200" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.code" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <!-- <vxe-column field="coloumType" title="字段类型" width="200" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.coloumType" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>-->
        <vxe-column field="coloumType" title="字段类型" width="100" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ formatCommon(coloumTypeList, row.coloumType) }}</span>
          </template>
          <template #edit="{ row }">
            <vxe-select v-model="row.coloumType" transfer>
              <vxe-option v-for="item in coloumTypeList" :key="item.id" :value="item.code" :label="item.name"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>

        <vxe-column field="common" title="字段说明" width="200" :edit-render="{}">
          <template #edit="{ row}">
            <vxe-input v-model="row.common" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="state" title="是否启用">
          <template #default="{ row }">
            <el-switch v-model="row.state" inline-prompt active-text="是" inactive-text="否"></el-switch>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import XEClipboard from 'xe-clipboard';
import { IsEmpty } from '@/utils/common';

let store = AppStore();
defineExpose({ initPage });
let interfaceParamId = ref(null);
let interfaceType = ref(null);
let detailList: any = reactive([]);
let rloading = ref(false);
let coloumTypeList = reactive([]);

function initPage(row: any, type) {
  interfaceParamId.value = row;
  interfaceType.value = type;
  findInterfaceParamList();
  getDictItemsList();
}

//批量获取字典
async function getDictItemsList() {
  coloumTypeList.length = 0;
  let dictTreeTypeCodes: any = ['interfaceColoumType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceColoumType');
  coloumTypeList.push(...severityType.detailDataList);
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findInterfaceParamList() {
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  if (isEmpty(interfaceParamId.value)) {
    rloading.value = false;
    return;
  }
  const url = '/api/sys/getInterfaceDictParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { dictId: interfaceParamId.value, type: interfaceType.value }
    })
    .then((res: any) => {
      detailList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('请选择场景', VxeNotifyType.error);
    });
}

function addInterfaceParam() {
  if (isEmpty(interfaceParamId)) {
    VxeMessage('请选择方法', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      dictId: interfaceParamId.value,
      code: '',
      common: '',
      type: interfaceType.value,
      state: true,
      coloumType: '1',
      seq: detailList.length + 1,
      orgId: store.userInfo.orgId
    };
    detailList.push(record);
  }
}

// 左侧保存
async function saveBathInterfaceParam() {
  if (isEmpty(interfaceParamId)) {
    VxeMessage('请选择接口', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.InterfaceParamTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = detailList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateDetail = [] as any[];
      updateRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          seq: e.seq,
          dictId: e.dictId,
          code: e.code,
          common: e.common,
          type: e.type,
          coloumType: e.coloumType,
          state: e.state,
          orgId: e.orgId
        };

        sveOrupdateDetail.push(iDetail);
      });
      InsertRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          seq: e.seq,
          dictId: e.dictId,
          code: e.code,
          common: e.common,
          type: e.type,
          coloumType: e.coloumType,
          state: e.state,
          orgId: e.orgId
        };
        sveOrupdateDetail.push(iDetail);
      });

      if (sveOrupdateDetail.length > 0) {
        const url = '/api/sys/editInterfaceDictParam';
        const obj: any = {};
        obj.list = sveOrupdateDetail;
        obj.type = interfaceType.value;
        obj.dictId = interfaceParamId.value;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            findInterfaceParamList();
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deleteInterfaceParam() {
  const sltDetails = (proxy.$refs.InterfaceParamTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDetailList = sltDetails.filter((p: any) => !isEmpty(p.id));
        if (delDetailList.length > 0) {
          const data = { ids: delDetailList.map((p) => p.id) };
          const url = '/api/sys/deleteInterfaceDictParam';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findInterfaceParamList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeDetailList = sltDetails.filter((p: any) => isEmpty(p.id));
        if (removeDetailList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.InterfaceParamTableRef;
          if ($Xtable) {
            for (const removeRow of removeDetailList) {
              detailList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
/**复制 */
function copy() {
  VxeMessage('已复制到剪贴板', VxeNotifyType.success);
  sessionStorage.setItem('outparamcopy', JSON.stringify(detailList));
}
/**粘贴 */
function paste() {
  const a = sessionStorage.getItem('outparamcopy');
  const b = JSON.parse(a);
  if (IsEmpty(b) || IsEmpty(a)) {
    VxeMessage('没有要粘贴的数据', VxeNotifyType.warning);
    return;
  }
  if (!interfaceParamId.value) {
    VxeMessage('请选择场景', VxeNotifyType.warning);
    return;
  }
  b.forEach(e => {
    e.dictId = interfaceParamId.value;
    e.type = interfaceType.value;
    e.id = null;
  });
  Object.assign(detailList, b);
}
</script>

<style lang="scss" scoped>
#InterfaceParamDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
